/**    
 * @Description: 博客园地址：https://www.cnblogs.com/zumengjie/      
 * @author: 顶风少年   
 * @date: 2021年4月5日 下午3:47:39
 */

package datang.dtdb.transaction.managed;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import datang.dtdb.exceptions.TransactionException;
import datang.dtdb.session.TransactionIsolationLevel;
import datang.dtdb.transaction.Transaction;

/**
 * 不实现提交和回滚，但可以关闭连接
 */
public class ManagedTransaction implements Transaction {

	private boolean closeConnection;

	private DataSource dataSource;

	/**
	 * 保存该连接用于提交或回滚事务
	 */
	private Connection connection;

	/**
	 * 用户指定隔离级别
	 */
	private TransactionIsolationLevel level;

	public ManagedTransaction(DataSource dataSource, TransactionIsolationLevel level, boolean closeConnection) {
		this.dataSource = dataSource;
		this.closeConnection = closeConnection;
		this.level = level;
	}

	/**
	 * 关闭连接
	 */
	@Override
	public void close() {
		if (closeConnection) {
			try {
				connection.close();
			} catch (Exception e) {
				throw new TransactionException("关闭连接异常", e);
			}

		}
	}

	/**
	 * 是否可以关闭
	 */
	public void setCloseConnection(boolean closeConnection) {
		this.closeConnection = closeConnection;
	}

	@Override
	public void commit() {
	}

	@Override
	public void rollback() {
	}

	@Override
	public Connection getConnection() {
		try {
			connection = dataSource.getConnection();
			connection.setTransactionIsolation(level.getLevel());
			return connection;
		} catch (SQLException e) {
			throw new TransactionException("ManagedTransaction获取连接失败", e);
		}
	}

}
